package cn.mumzone.pos.ui.fragment.inventory;

import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatImageView;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.ruffian.library.widget.REditText;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.event.DateChangedEvent;
import cn.mumzone.pos.event.MoreViewChangeEvent;
import cn.mumzone.pos.event.SearchInventoryEvent;
import cn.mumzone.pos.presenter.InitMoreViewPresenter;
import cn.mumzone.pos.presenter.contract.MoreViewContract;
import cn.mumzone.pos.ui.adapter.inventory.ADA_InventoryForVp;
import cn.mumzone.pos.ui.adapter.inventory.ADA_InventoryNavigation;
import cn.mumzone.pos.ui.widgets.PosTimePickerView;
import cn.mumzone.pos.ui.widgets.tablayout.MagicIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.ViewPagerHelper;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.CommonNavigator;
import cn.mumzone.pos.util.DateHolder;

/**
 * Created By Dlx
 * on 2019/9/25
 */
public class FRA_Inventory extends BaseFragment<InitMoreViewPresenter> implements MoreViewContract.View, ADA_InventoryNavigation.OnTitleViewClickListener {
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.ic_go_previous_day)
    AppCompatImageView icGoPreviousDay;
    @BindView(R.id.ic_go_next_day)
    AppCompatImageView ivGoNextDay;
    @BindView(R.id.rl_date)
    RelativeLayout rlDate;
    @BindView(R.id.viewpager_content)
    ViewPager vpContent;
    @BindView(R.id.indicator_bill)
    MagicIndicator indicatorBill;
    @BindView(R.id.bill_delete_iv)
    ImageView ivDelete;
    @BindView(R.id.et_search)
    REditText etSearch;
    @BindView(R.id.btn_search)
    Button btnSearch;

    private PosTimePickerView posTimePickerView;

    private ADA_InventoryForVp adapter;

    private Date currentDay;

    final String[] titles = {"全部", "未开始", "进行中", "已完成"};

    @Override
    protected void onUserVisible() {
        RxBus.getDefault().post(new DateChangedEvent(0, DateChangedEvent.TYPE_INVENTORY));
    }

    @Override
    protected void initEventAndData() {

        mPresenter.initEvents();
        adapter = new ADA_InventoryForVp(getChildFragmentManager());
        vpContent.setAdapter(adapter);

        initMagicIndicator();
        initEditTextListener();

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        int nowYear = endDate.get(Calendar.YEAR);
        startDate.set(nowYear - 2, 0, 1);
        posTimePickerView = new PosTimePickerView.PosTimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                currentDay = date;
                setDateChanged(date);
            }
        }).isDialog(true).isCyclic(false).setOutSideCancelable(true)
                .setTitleText("选择时间")
                .setType(new boolean[]{true, true, true, false, false, false})
                .setDate(endDate)
                .setRangDate(startDate, endDate)
                .build();
        setDateChanged(endDate.getTime());
    }

    private void initMagicIndicator() {

        indicatorBill.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setAdjustMode(true);
        ADA_InventoryNavigation titleAdapter = new ADA_InventoryNavigation(titles);
        titleAdapter.setListener(this);
        commonNavigator.setAdapter(titleAdapter);
        indicatorBill.setNavigator(commonNavigator);
        ViewPagerHelper.bind(indicatorBill, vpContent);
    }

    private void setDateChanged(Date currentDay) {
        DateHolder.INSTANCE.setInventoryDate(currentDay.getTime());
        tvDay.setText(String.format("%s %s", AppDateUtil.getDateToString(currentDay.getTime(), AppDateUtil.YYYY_MM_DD1),
                AppDateUtil.getWeekOfDate(currentDay.getTime())));
        if (AppDateUtil.isSameDay(currentDay, new Date())) {
            ivGoNextDay.setVisibility(View.INVISIBLE);
        } else {
            ivGoNextDay.setVisibility(View.VISIBLE);
        }

        if (null != this.currentDay) {

            RxBus.getDefault().post(new DateChangedEvent(currentDay.getTime(), DateChangedEvent.TYPE_INVENTORY));
            DateHolder.INSTANCE.setInventroyKey("");
            etSearch.setText("");

        }
        this.currentDay = currentDay;

    }

    @Override
    protected int getLayout() {
        return R.layout.fra_inventory;
    }


    @OnClick({R.id.ic_go_previous_day, R.id.ic_go_next_day, R.id.bill_delete_iv, R.id.btn_search, R.id.iv_back, R.id.tv_day})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ic_go_previous_day:
                if (getCurrentFragment().isRefreshing()) {
                    return;
                }
                currentDay = new Date(AppDateUtil.getPreviousDay(currentDay.getTime()));
                setDateChanged(currentDay);
                break;
            case R.id.ic_go_next_day:
                if (getCurrentFragment().isRefreshing()) {
                    return;
                }
                currentDay = new Date(AppDateUtil.getNextDay(currentDay.getTime()));
                setDateChanged(currentDay);
                break;
            case R.id.tv_day:
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDay);
                posTimePickerView.setDate(calendar);
                posTimePickerView.show();
                break;
            case R.id.bill_delete_iv:
                setViewVisibility(ivDelete, false);
                etSearch.setText("");
                RxBus.getDefault().post(new DateChangedEvent(0, DateChangedEvent.TYPE_INVENTORY));
                break;
            case R.id.btn_search:
                String key = etSearch.getText().toString().trim();
                if (StringUtils.isEmpty(key)) {
                    PosToast.INSTANCE.makeShortToast(mContext, "请输入搜索内容");
                    return;
                }
                DateHolder.INSTANCE.setInventroyKey(key);
                RxBus.getDefault().post(new SearchInventoryEvent(key));
                vpContent.setCurrentItem(0, false);
                break;
            case R.id.iv_back:
                RxBus.getDefault().post(new MoreViewChangeEvent(MoreViewChangeEvent.MORE_VIE_HOME));
                break;
        }
    }

    private void initEditTextListener() {
        etSearch.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    btnSearch.setEnabled(true);
                    setViewVisibility(ivDelete, true);
                } else if (s.toString().length() == 0) {
                    btnSearch.setEnabled(false);
                    setViewVisibility(ivDelete, false);
                    DateHolder.INSTANCE.setInventroyKey("");
                    RxBus.getDefault().post(new DateChangedEvent(0, DateChangedEvent.TYPE_INVENTORY));
                }
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);

                    RxBus.getDefault().post(new SearchInventoryEvent(etSearch.getText().toString().trim()));
                }
                return false;
            }
        });
    }

    @Override
    public void onTitleClick(int position) {
        vpContent.setCurrentItem(position, false);
    }

    @Override
    public void onBackEvent() {
        etSearch.setText("");
        currentDay = new Date();
        tvDay.setText(String.format("%s %s", AppDateUtil.getDateToString(currentDay.getTime(), AppDateUtil.YYYY_MM_DD1),
                AppDateUtil.getWeekOfDate(currentDay.getTime())));
        DateHolder.INSTANCE.setInventoryDate(currentDay.getTime());
        ivGoNextDay.setVisibility(View.INVISIBLE);
        DateHolder.INSTANCE.setInventroyKey("");
    }

    private FRA_InventoryItem getCurrentFragment() {
        return (FRA_InventoryItem) adapter.getItem(vpContent.getCurrentItem());
    }
}
